# -*- coding: UTF-8 -*-
import os
import time
from flask import Flask,render_template,flash,url_for,redirect,session,request
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from datetime import datetime
from flask_bootstrap import Bootstrap
import flask_excel as excel

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
bootstrap=Bootstrap(app)
excel.init_excel(app)
app.config['SECRET_KEY'] = 'a62f2225bf70bfaccbc7f1ef2a397836717377de'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)

class UserForm(FlaskForm):
    name = StringField('花名：',validators=[Required()])
    user_state = StringField('状态：',validators=[Required()])#1在职，0离职
    submit = SubmitField('提交')

class AssetForm(FlaskForm):
    number = StringField('编号：',validators=[Required()])
    asset_state = StringField('状态：',validators=[Required()])#1在用，0仓库，2报废
    name = StringField('花名：',validators=[Required()])
    cpu = StringField('CPU：')
    memory = StringField('内存：')
    disk = StringField('硬盘：')
    display = StringField('显示：')
    notes = StringField('备注：')
    submit = SubmitField('提交')

class User(db.Model):
    __tablename__ = 'user'
    user_id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(20),index=True,nullable=False)
    user_state = db.Column(db.Integer,nullable=False)#1在职，0离职
    user_ctime = db.Column(db.String,default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    user_utime = db.Column(db.String,default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), onupdate=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

class Asset(db.Model):
    __tablename__ = 'asset'
    asset_id = db.Column(db.Integer,primary_key=True)
    number = db.Column(db.String(30),nullable=False)
    name = db.Column(db.String(20),index=True,nullable=False)
    asset_state = db.Column(db.Integer,nullable=False)#1在用，0仓库，2报废
    cpu = db.Column(db.String(20))
    memory = db.Column(db.String(50))
    disk = db.Column(db.String(50))
    display = db.Column(db.String(50))
    notes = db.Column(db.String(50))
    records = db.relationship('Record',backref='asset')
    asset_ctime = db.Column(db.String,default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    asset_utime = db.Column(db.String, default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), onupdate=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

class Record(db.Model):
    __tablename__ = 'record'
    record_id = db.Column(db.Integer,primary_key=True)
    asset_id = db.Column(db.Integer,db.ForeignKey('asset.asset_id'))
    record = db.Column(db.String(255))
    record_ctime = db.Column(db.String,default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
#首页
@app.route('/')
def index():
    # print ("index")
    return render_template('index.html')
#员工
@app.route('/user')
def user():
    # print ("user")
    return render_template('user.html')
#资产
@app.route('/asset')
def asset():
    # print ("asset")
    return render_template('asset.html')

@app.route('/record/<asset_id>')
def record(asset_id=None):
    page = request.args.get('page',1,type=int)
    pagination = Record.query.filter_by(asset_id=asset_id).paginate(page,per_page=20)
    record = pagination.items
    return render_template('/record.html', record=record,pagination=pagination,asset_id=asset_id)

#增加
@app.route('/add/<search>',methods=['GET', 'POST'])
def add(search=None):
    if search == 'user':
        userform = UserForm()
        if userform.validate_on_submit():
            user = User(name=userform.name.data,user_state=userform.user_state.data)
            db.session.add(user)
            db.session.commit()
            flash('人员添加成功,点击查看全部.')
            return redirect(url_for('add',search='user'))
        return render_template('user_add.html',userform=userform)
    elif search == 'asset':
        assetform = AssetForm()
        if assetform.validate_on_submit():
            asset = Asset(number = assetform.number.data,name = assetform.name.data,asset_state = assetform.asset_state.data,\
                            cpu = assetform.cpu.data,memory = assetform.memory.data,disk = assetform.disk.data,\
                            display = assetform.display.data,notes = assetform.notes.data\
                        )
            db.session.add(asset)
            db.session.commit()
            records = "*增加*编号:%s, 花名:%s, 状态:%s, CPU:%s, 内存:%s, 硬盘:%s, 显示:%s, 备注:%s " % \
            (asset.number,asset.name,asset.asset_state,asset.cpu,asset.memory,asset.disk,asset.display,asset.notes)
            record = Record(asset_id = asset.asset_id,record=records)
            db.session.add(record)
            db.session.commit()
            flash('资产添加成功,点击查看全部.')
            return redirect(url_for('add',search='asset'))
        return render_template('asset_add.html',assetform=assetform)

#查找
@app.route('/select/<search>',methods=['GET', 'POST'])
def select(search=None):
    if search == 'user':
        if request.args.get('item'):
            name = request.args.get('item')
            user = User.query.filter_by(name=name)
            return render_template('/user_selcet.html', user=user)
        else:
            page = request.args.get('page',1,type=int)
            pagination = User.query.paginate(page,per_page=20)
            user = pagination.items
            return render_template('/user_selcet.html', user=user, pagination=pagination)
    elif search == 'asset':
        if request.args.get('item'):
            number = request.args.get('item')
            asset = Asset.query.filter_by(number=number)
            return render_template('/asset_selcet.html', asset=asset)
        else:
            page = request.args.get('page',1,type=int)
            pagination = Asset.query.paginate(page,per_page=20)
            asset = pagination.items
            return render_template('/asset_selcet.html', asset=asset, pagination=pagination)

@app.route('/editor/<search>',methods=['GET', 'POST'])
def editor(search=None):
    if search == 'user':
        userform = UserForm()
        user_id = request.args.get('id')
        if userform.validate_on_submit():
            user = User.query.filter_by(user_id=user_id).first()
            user.name = userform.name.data
            user.user_state = userform.user_state.data
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('select',search='user'))
        user = User.query.filter_by(user_id=user_id).first()
        userform.name.data = user.name
        userform.user_state.data = user.user_state
        return render_template('user_add.html',userform=userform)
    elif search == 'asset':
        assetform = AssetForm()
        asset_id = request.args.get('id')
        if assetform.validate_on_submit():
            asset = Asset.query.filter_by(asset_id=asset_id).first()
            asset.number = assetform.number.data
            asset.cpu = assetform.cpu.data
            asset.asset_state = assetform.asset_state.data
            asset.name = assetform.name.data
            asset.memory = assetform.memory.data
            asset.disk = assetform.disk.data
            asset.display = assetform.display.data
            asset.notes = assetform.notes.data
            db.session.add(asset)
            db.session.commit()
            # asset = Asset.query.filter_by(asset_id=asset_id).first()
            records = "*更新*编号:%s, 花名:%s, 状态:%s, CPU:%s, 内存:%s, 硬盘:%s, 显示:%s, 备注:%s " % \
            (asset.number,asset.name,asset.asset_state,asset.cpu,asset.memory,asset.disk,asset.display,asset.notes)
            record = Record(asset_id = asset.asset_id,record=records)
            db.session.add(record)
            db.session.commit()
            return redirect(url_for('select',search='asset'))
        asset = Asset.query.filter_by(asset_id=asset_id).first()
        assetform.number.data = asset.number
        assetform.cpu.data = asset.cpu
        assetform.asset_state.data = asset.asset_state
        assetform.name.data = asset.name
        assetform.memory.data = asset.memory
        assetform.disk.data = asset.disk
        assetform.display.data = asset.display
        assetform.notes.data = asset.notes
        return render_template('asset_add.html',assetform=assetform)
@app.route("/export", methods=['GET'])
def export():
    return excel.make_response_from_tables(db.session, [User, Asset], "xls",file_name='Asset-%s.xls' % time.strftime('%Y%m%d%H%M'))

@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(error):
    return render_template('500.html'), 500
if __name__ == '__main__':
    app.run()
